package com.android.antelopeapp.fragment;

import android.support.v4.app.Fragment;
import android.util.Log;

import java.util.HashMap;
import java.util.Map;

public class FragmentFactory {
    private FragmentFactory(){}
    private static FragmentFactory instance;

    private Map<String,Fragment> fragmentHashMap = new HashMap<>();

    private Fragment getFragmentByClass(Class cls){
        if(Fragment.class.isAssignableFrom(cls)) {
            try {
                if(fragmentHashMap.get(cls.getName())==null){
                    fragmentHashMap.put(cls.getName(),(Fragment) cls.newInstance());
                }
                return fragmentHashMap.get(cls.getName());
            }catch (InstantiationException | IllegalAccessException e){
                Log.d(FragmentFactory.class.getName(),e.getMessage());
            }
        }
        return null;
    }

    public static FragmentFactory getInstance(){
        if(instance == null){
            instance =  new FragmentFactory();
        }
        return instance;
    }
    public static Fragment getInstanceByTabId(int index) {
        Fragment fm = null;
        switch (index) {
            case 0:
               fm = new CNHomeFragment();
               //fm = getInstance().getFragmentByClass(CNHomeFragment.class);
                break;
            case 1:
               fm = new CommodityFragment();
            //  fm = getInstance().getFragmentByClass(CommodityFragment.class);
                break;
            /*
            case 2:
                fm = new CommunityFragment();
                break;
            case 3:
                fm = new MineFragment();
                break;
            */
            default:
                Log.w("FragmentFacoty", "index=" + index + " 未找到对应的Fragment");
                fm = new CNHomeFragment();
//                fm = getInstance().getFragmentByClass(CNHomeFragment.class);
                break;
        }
        return fm;
    }


}
